package com.example.demo.msg.aio.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

public class ClientHandler implements CompletionHandler<Void,ClientHandler>,Runnable{

    private AsynchronousSocketChannel channel;

    private CountDownLatch latch;

    private int port;

    private String ip;

    public ClientHandler(int port,String ip) {
        this.ip = ip;
        this.port = port;


        try {
            channel = AsynchronousSocketChannel.open();
        } catch (IOException e) {

            e.printStackTrace();
        }


    }

    @Override
    public void run() {

        latch = new CountDownLatch(1);

        channel.connect(new InetSocketAddress(ip,port),this,this);

        try {
            latch.await();
        } catch (InterruptedException e) {

            e.printStackTrace();
        }

        try {
            channel.close();
        } catch (IOException e) {

            e.printStackTrace();
        }


    }

    @Override
    public void completed(Void aVoid, ClientHandler clientHandler) {
        System.out.println("客户端成功连接到服务器...");
    }

    @Override
    public void failed(Throwable throwable, ClientHandler clientHandler) {
        System.err.println("连接服务器失败...");
        throwable.printStackTrace();

        try {
            channel.close();

            latch.countDown();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }

    public void sendMsg(String msg){
        byte[] req = msg.getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);

        writeBuffer.flip();
        channel.write(writeBuffer,writeBuffer,new WriteHandle(channel,latch));

    }
}